import React, { useState, useEffect, useRef } from 'react';

/**
 * 消息接口定义
 * @interface Message
 * @property {number} id - 消息ID
 * @property {string} type - 消息类型
 * @property {string} from - 发送者
 * @property {string} to - 接收者
 * @property {string} content - 消息内容
 * @property {string} timestamp - 时间戳
 */
export interface Message {
  id: number;
  type: string;
  from: string;
  to: string;
  content: string;
  timestamp: string;
}

/**
 * 聊天窗口组件属性接口
 * @interface ChatWindowProps
 * @property {string} currentUser - 当前登录用户
 * @property {string} selectedUser - 选中的用户
 * @property {Message[]} messages - 消息列表
 * @property {function(string): void} onSendMessage - 发送消息回调函数
 * @property {boolean} isConnected - WebSocket连接状态
 */
export interface ChatWindowProps {
  currentUser: string;
  selectedUser: string;
  messages: Message[];
  onSendMessage: (content: string) => void;
  isConnected: boolean;
}

const ChatWindow: React.FC<ChatWindowProps> = ({
  currentUser,
  selectedUser,
  messages,
  onSendMessage,
  isConnected
}) => {
  const [inputMessage, setInputMessage] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (inputMessage.trim()) {
      onSendMessage(inputMessage);
      setInputMessage('');
    }
  };

  const formatTime = (timestamp: string) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  };

  if (!selectedUser) {
    return (
      <div className="chat-area">
        <div style={{
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          height: '100%',
          color: '#666',
          fontSize: '18px'
        }}>
          请从左侧选择用户开始聊天
        </div>
      </div>
    );
  }

  return (
    <div className="chat-area">
      <div className="chat-header">
        <h3>与 {selectedUser} 的对话</h3>
        <div style={{
          fontSize: '14px',
          color: isConnected ? '#4caf50' : '#f44336',
          marginTop: '5px'
        }}>
          {isConnected ? '已连接' : '连接断开'}
        </div>
      </div>

      <div className="messages-container">
        {messages.length === 0 ? (
          <div style={{
            textAlign: 'center',
            color: '#666',
            fontStyle: 'italic',
            padding: '40px'
          }}>
            暂无消息，开始对话吧！
          </div>
        ) : (
          messages.map((message) => (
            <div
              key={message.id}
              className={`message ${message.from === currentUser ? 'own' : 'other'}`}
            >
              <div className="message-bubble">
                {message.from !== currentUser && (
                  <div className="message-sender">{message.from}</div>
                )}
                <div>{message.content}</div>
                <div className="message-time">
                  {formatTime(message.timestamp)}
                </div>
              </div>
            </div>
          ))
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="message-input-container">
        <form className="message-input-form" onSubmit={handleSubmit}>
          <input
            type="text"
            className="message-input"
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            placeholder="输入消息..."
            disabled={!isConnected}
          />
          <button 
            type="submit" 
            className="send-btn"
            disabled={!inputMessage.trim() || !isConnected}
          >
            发送
          </button>
        </form>
      </div>
    </div>
  );
};

export default ChatWindow;